<?php
/**
 * Created by PhpStorm.
 * User: william
 * Date: 2021/2/19
 * Time: 13:45
 */
require_once DXW_PAY_DIR."wechatH5Pay.php";

class MallController extends Controller{
    public function init(){
    }


    //产品详情
    public function actionProductdetail(){

        $product_id=Tools::_get("product_id","","");//产品id

        if($product_id){
            $info= ProductModel::create()->fetchOne("id = '{$product_id}' ","*");
            $info['detail_image']=explode(",",$info['detail_image']);
            $info['recommend']=ProductModel::create()->fetchAll("id != '{$product_id}' and state = 1 ","0",10,"is_top desc","id,name,cover_image,price,title,service,remark");
        }else{
            $info= ProductModel::create()->fetchOne("state = 1 and is_delete = 1 and is_top = 1 ","*");

            $info['detail_image']=explode(",",$info['detail_image']);
            $info['recommend']=ProductModel::create()->fetchAll("is_top != 1 and state = 1 and is_delete = 1 ",0,10,"id desc","id,name,cover_image,price,title,service,remark");
        }


        $this->jout(200,$info,"");
    }

    //订单创建
    public function actionOrdercreate(){
        $uuid=Tools::_get("uuid","","");//uuid
        $product_id=Tools::_get("product_id","","");//产品id
        $mobile=Tools::_get("mobile","","/^1[3456789]{1}\d{9}$/");//手机号
        $num=Tools::_get("num","","");//数量
        $consignee=Tools::_get("consignee","","");//收货人
        $area=Tools::_get("area","","");//区域
        $address=Tools::_get("address","","");//地址
        $total_price=Tools::_get("total_price","","");//总价
        $remark=Tools::_get("remark","","");//备注


        if(!$uuid){
            $this->jout(203,"","uuid不能为空！");
        }

        if(!$product_id){
            $this->jout(203,"","产品id不能为空！");
        }

        if(!$mobile){
            $this->jout(203,"","手机号不能为空！");
        }
        if(!$num){
            $this->jout(203,"","数量不能为空！");
        }
        if(!$consignee){
            $this->jout(203,"","收货人不能为空！");
        }
        if(!$area){
            $this->jout(203,"","区域不能为空！");
        }

        if(!$address){
            $this->jout(203,"","地址不能为空！");
        }
        if(!$total_price){
            $this->jout(203,"","价格不能为空！");
        }

        $data=array();
        $data['order_sn']=date("Ymdhis").rand(10000000, 99999999)."znms";
        $data['product_id']=$product_id;
        $data['mobile']=$mobile;
        $data['num']=(int)$num;
        $data['consignee']=$consignee;
        $data['area']=$area;
        $data['address']=$address;
        $data['state']=1;
        $data['remark']=$remark;
        $data['uuid']=  $uuid;
        $data['pay_way']=  "微信支付";
        $data['created_date']=time();

        //验证价格
        $info= ProductModel::create()->fetchOne("id = '{$product_id}' and state= 1 ","*");
        if(empty($info)){
            $this->jout(203,"","商品已失效！");
        }
        $total_price_check=($info['price']*100*$data['num'])/100;
        if($total_price_check == $total_price){
            $data['total_price']=$total_price;
        }else{
            $data['total_price']=$total_price_check;
        }
        $order_info=OrderModel::create()->fetchOne("uuid = '{$uuid}'","*","created_date desc");
        if(!empty($order_info)){
            if(($order_info['created_date']+10)>time()){
                $this->jout(203,"","请勿重复提交订单！");
            }
        }

        $id=OrderModel::create()->add_($data);

        $info= ProductModel::create()->fetchOne("id = '{$product_id}' ","*");
        if($id !==false){
            $this->actionUnifiedorder($data['order_sn'],$uuid,$product_id,$data['total_price']);

            //$this->jout(200,array("order_sn"=>$data['order_sn']));
        }else{
            $this->jout(203,"","订单创建失败");
        }

    }


    public function actionUnifiedorder($order_sn,$uuid,$product_id,$total_price){

        $wechatAppPay = new \wechatAppPay();
        $info= ProductModel::create()->fetchOne("id = '{$product_id}' ","*");
        $params['body'] = $info['title']."-".$info['name'];                       //商品描述
        $params['out_trade_no'] = $order_sn;    //自定义的订单号（外部订单号）
        $params['total_fee'] = $total_price*100;                       //订单金额 只能为整数 单位为分
        $params['trade_type'] = 'MWEB';                   //交易类型 JSAPI | NATIVE | APP | WAP
        $params['scene_info'] = '{"h5_info": {"type":"Wap","wap_url": "https://mall.xcydhn.com","wap_name": "智能门锁"}}';
        $result = $wechatAppPay->unifiedOrder( $params );

        $data['mweb_url'] = $result['mweb_url'].'&redirect_url='.urlencode('https://mall.xcydhn.com/#/trapage?uuid='.$uuid."&order_sn=".$order_sn);//redirect_url 是支付完成后返回的页面

        $this->jout(200,$data);
    }

     public function actionNotify(){


         $testxml  = file_get_contents("php://input");
         $jsonxm = simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA);
         $jsonxml = json_encode($jsonxm);

         $fp = fopen("../cache/file/abc1.txt", "a+");
         fwrite($fp, $jsonxml);
         fclose($fp);

         $jsonxmls=json_decode($jsonxml,true);
         $_REQUEST["out_trade_no"] = $jsonxmls['out_trade_no'];//外部订单号
         if(isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"] != ""&&$jsonxmls['result_code']=='SUCCESS'&&$jsonxmls['return_code']=='SUCCESS') {

             $wechatAppPay = new \wechatAppPay();
             $result = $wechatAppPay->orderQuery($_REQUEST["out_trade_no"]);

             if ($result['trade_state'] == "SUCCESS") {
                  OrderModel::create()->update_(array("state" => 2,"json_data"=>$jsonxml), "  order_sn = '{$_REQUEST["out_trade_no"]}'");
             }else{
                 OrderModel::create()->update_(array("json_data"=>$jsonxml), "  order_sn = '{$_REQUEST["out_trade_no"]}'");
             }

             echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';

         }else{
             OrderModel::create()->update_(array("json_data"=>$jsonxml), "  order_sn = '{$_REQUEST["out_trade_no"]}'");
             echo '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
         }




     }

    //查询微信后台订单支付状态改订单状态
    public function actionQuery(){
        $data['order_sn'] = Tools::_get("order_sn",'',"");
        parent::check_primary_key_null($data['order_sn']);

        $row = OrderModel::create()->fetchOne("  order_sn = '{$data["order_sn"]}'");
        if(empty($row)){
            $this->jout(203,'','数据没有找到！');
        }
        $_REQUEST["out_trade_no"] = $row['order_sn'];//外部订单号
        if(isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"] != ""){
            $out_trade_no = $_REQUEST["out_trade_no"];

            $wechatAppPay = new \wechatAppPay();
            $result=$wechatAppPay->orderQuery($out_trade_no);


            if ($result['trade_state'] == "SUCCESS"){
                $result1 = OrderModel::create()->update_(array("state"=>2),"  order_sn = '{$data["order_sn"]}'");
                if ($result1!==false){
                    $this->jout(200,$result['trade_state'],"支付成功！");
                }else{
                    $this->jout(203,$result['trade_state'],"支付成功,订单回调失败！");
                }
            }else{
                $this->jout(203,$result['trade_state'],"支付失败！");
            }


        }

    }

     //订单记录
    public function actionMyrecord(){
        $uuid=Tools::_get("uuid","","");//uuid
        //$order_sn=Tools::_get("order_sn","","");//订单号（支付完成改订单状态的）

        if(!$uuid){
            $this->jout(203,"","uuid不能为空！");
        }
//        if($order_sn){
//            $this->actionQuery();
//        }

        $sql="SELECT
	            z_order.id,z_order.total_price,z_order.num,z_product.cover_image,z_product.price,z_product.name,z_product.title
              FROM z_order 
              INNER JOIN z_product ON  z_product.id =z_order.product_id 
              WHERE  uuid = '{$uuid}' and z_order.state = 2 ORDER BY   z_order.created_date DESC  ";


        $list = query_sql($sql,"znms_product");
        $this->jout(200,$list);

    }

      //订单记录详情
    public function actionRecorddetail(){

        $id=Tools::_get("id","","");//订单id

        if(!$id){
            $this->jout(203,"","订单id不能为空！");
        }

        $sql="SELECT
	            z_order.id,z_product.cover_image,z_product.name,z_product.title,z_product.price,z_order.total_price,z_order.num,z_product.service,
	            z_order.consignee,z_order.mobile,z_order.area,z_order.address,
	            z_order.order_sn,z_order.pay_way,FROM_UNIXTIME(z_order.created_date,'%Y-%m-%d %H:%i:%S') as  created_date,z_order.remark
              FROM z_order 
              INNER JOIN z_product ON  z_product.id =z_order.product_id 
              WHERE  z_order.id = '{$id}' and z_order.state = 2 ";



        $list = query_sql($sql,"znms_product");
        if(!empty($list)){
            $this->jout(200,$list[0]);
        }else{
            $this->jout(200,$list);
        }


    }


}